<?php

namespace Itdashu\SwoftThirdPartyService\Service\Base;

/**
 * 自定义CURL文件类
 * Class MyCurlFile
 * @package WeChat\Contracts
 */
class MyCurlFile extends \stdClass
{
  /**
   * 当前数据类型
   * @var string
   */
  public $datatype = 'MY_CURL_FILE';

  /**
   * MyCurlFile constructor.
   * @param $fileName
   * @param string $mimeType
   * @param string $postName
   */
  public function __construct($fileName, $mimeType = '', $postName = '')
  {
    if (is_array($fileName)) {
      foreach ($fileName as $k => $v) {
        $this->{$k} = $v;
      }
    } else {
      $this->mimetype = $mimeType;
      $this->postname = $postName;
      $this->extension = pathinfo($fileName, PATHINFO_EXTENSION);
      if (empty($this->extension)) {
        $this->extension = 'tmp';
      }
      if (empty($this->mimetype)) {
        $this->mimetype = Tools::getExtMine($this->extension);
      }
      if (empty($this->postname)) {
        $this->postname = pathinfo($fileName, PATHINFO_BASENAME);
      }
      $this->content = base64_encode(file_get_contents($fileName));
      $this->tempname = md5($this->content) . ".{$this->extension}";
    }
  }

  /**
   * 获取文件信息
   * @return \CURLFile|string
   * @throws \Itdashu\SwoftThirdPartyService\Service\WeChat\Exceptions\LocalCacheException
   */
  public function get()
  {
    $this->filename = Tools::pushFile($this->tempname, base64_decode($this->content));
    if (class_exists('CURLFile')) {
      return new \CURLFile($this->filename, $this->mimetype, $this->postname);
    }
    return "@{$this->tempname};filename={$this->postname};type={$this->mimetype}";
  }

  /**
   * 类销毁处理
   */
  public function __destruct()
  {
    // Tools::delCache($this->tempname);
  }

}